package com.cookie.meetproject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cookie.framework.base.BaseUIActivity;
import com.cookie.framework.bmob.BmobManger;
import com.cookie.framework.entity.Constants;
import com.cookie.framework.gson.TokenBean;
import com.cookie.framework.manager.DialogManager;
import com.cookie.framework.manager.HttpManager;
import com.cookie.framework.utils.LogUtils;
import com.cookie.framework.utils.SpUtils;
import com.cookie.framework.view.DialogView;
import com.cookie.meetproject.fragment.ChatFragment;
import com.cookie.meetproject.fragment.MeFragment;
import com.cookie.meetproject.fragment.SquareFragment;
import com.cookie.meetproject.fragment.StartFragment;
import com.cookie.meetproject.service.CloudService;
import com.cookie.meetproject.ui.FirstUploadActivity;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseUIActivity implements View.OnClickListener {

    //申请运行时权限的code
    private static final int PERMISSION_REQUEST_CODE = 1000;

    private FrameLayout mainLayout;
    //星球
    private ImageView ivStar;
    private TextView tvStar;
    private LinearLayout llStar;
    private StartFragment startFragment = null;
    private FragmentTransaction starTransation;

    //广场
    private ImageView ivSquare;
    private TextView tvSquare;
    private LinearLayout llSquare;
    private SquareFragment squareFragment;
    private FragmentTransaction squareTransation;

    //聊天
    private ImageView ivChat;
    private TextView tvChat;
    private LinearLayout llChat;
    private ChatFragment chatFragment;
    private FragmentTransaction chatTransation;

    //我的
    private ImageView ivMe;
    private TextView tvMe;
    private LinearLayout llMe;
    private MeFragment meFragment;
    private FragmentTransaction meTransation;

    private Disposable disposable;

    /**
     * 1.初始化Fragment
     * 2.显示Fragment
     * 3.隐藏所有的Fragment
     * 4.恢复Fragment
     * 优化的手段
     */

    //跳转上传头像的回调requestCode
    public static final int UPLOAD_REQUEST_CODE = 1002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        requestPermission();
        mainLayout = (FrameLayout) findViewById(R.id.main_layout);
        ivStar = (ImageView) findViewById(R.id.iv_star);
        tvStar = (TextView) findViewById(R.id.tv_star);
        llStar = (LinearLayout) findViewById(R.id.ll_star);
        ivSquare = (ImageView) findViewById(R.id.iv_square);
        tvSquare = (TextView) findViewById(R.id.tv_square);
        llSquare = (LinearLayout) findViewById(R.id.ll_square);
        ivChat = (ImageView) findViewById(R.id.iv_chat);
        tvChat = (TextView) findViewById(R.id.tv_chat);
        llChat = (LinearLayout) findViewById(R.id.ll_chat);
        ivMe = (ImageView) findViewById(R.id.iv_me);
        tvMe = (TextView) findViewById(R.id.tv_me);
        llMe = (LinearLayout) findViewById(R.id.ll_me);

        llStar.setOnClickListener(this);
        llSquare.setOnClickListener(this);
        llChat.setOnClickListener(this);
        llMe.setOnClickListener(this);

        //设置文本
        tvStar.setText(getString(R.string.text_main_star));
        tvSquare.setText(getString(R.string.text_main_square));
        tvChat.setText(getString(R.string.text_main_chat));
        tvMe.setText(getString(R.string.text_main_me));

        initFragment();

        //切换默认的选项卡
        checkMainTab(0);
        //检查tokens
        checkToken();

        //模拟数据
         //SimulationData.testData();
    }

    //检查token
    private void checkToken() {
        //获取token 需要三个参数 1.用户id 2.头像地址 3.昵称
        String token = SpUtils.getInstance().getString(Constants.SP_TOKEN, "");
        if (!TextUtils.isEmpty(token)) {
            //启动云服务连接融云服务
            startCloudService();
        } else {
            //1.有三个参数
            String tokenPhoto = BmobManger.getInstance().getUser().getTokenPhoto();
            String tokenNickName = BmobManger.getInstance().getUser().getTokenNickName();
            if (!TextUtils.isEmpty(tokenPhoto) && !TextUtils.isEmpty(tokenNickName)) {
                //创建token
                createToken();
            } else {
                //创建上传提示框
                createUploadDialog();
            }
        }
    }

    //启动云服务连接融云服务
    private void startCloudService() {
        startService(new Intent(this, CloudService.class));
    }

    //创建上传提示框
    private void createUploadDialog() {
        final DialogView uploadView = DialogManager.getInstance().initView(this, R.layout.dialog_first_upload);
        //外部点击不能消失
        uploadView.setCancelable(false);
        ImageView ivGoUpload = uploadView.findViewById(R.id.iv_go_upload);
        ivGoUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogManager.getInstance().hide(uploadView);
                FirstUploadActivity.startActivity(MainActivity.this, UPLOAD_REQUEST_CODE);
            }
        });
        DialogManager.getInstance().show(uploadView);
    }

    //创建token
    private void createToken() {
        /**
         * 1.去融云后台获取Token
         * 2.连接融云
         */
        final HashMap<String, String> map = new HashMap<>();
        map.put("userId", BmobManger.getInstance().getUser().getObjectId());
        map.put("name", BmobManger.getInstance().getUser().getTokenNickName());
        map.put("portraitUrl", BmobManger.getInstance().getUser().getTokenPhoto());
        //通过OkHttp请求token
        disposable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                //执行请求过程
                String json = HttpManager.getInstance().postCloudToken(map);
                emitter.onNext(json);
                emitter.onComplete();
            }
            //线程调度
        }).subscribeOn(Schedulers.newThread())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        parsingCloudToken(s);
                    }
                });
    }

    //解析token
    private void parsingCloudToken(String json) {
        TokenBean tokenBean = new Gson().fromJson(json, TokenBean.class);
        if (tokenBean.getCode() == 200) {
            if (!TextUtils.isEmpty(tokenBean.getToken())) {
                SpUtils.getInstance().putString(Constants.SP_TOKEN, tokenBean.getToken());
                startCloudService();
            }
        }
    }

    //初始化Fragment
    private void initFragment() {
        //星球
        if (startFragment == null) {
            startFragment = new StartFragment();
            starTransation = getSupportFragmentManager().beginTransaction();
            starTransation.add(R.id.main_layout, startFragment);
            starTransation.commit();
        }

        //广场
        if (squareFragment == null) {
            squareFragment = new SquareFragment();
            squareTransation = getSupportFragmentManager().beginTransaction();
            squareTransation.add(R.id.main_layout, squareFragment);
            squareTransation.commit();
        }

        //聊天
        if (chatFragment == null) {
            chatFragment = new ChatFragment();
            chatTransation = getSupportFragmentManager().beginTransaction();
            chatTransation.add(R.id.main_layout, chatFragment);
            chatTransation.commit();
        }

        //我的
        if (meFragment == null) {
            meFragment = new MeFragment();
            meTransation = getSupportFragmentManager().beginTransaction();
            meTransation.add(R.id.main_layout, meFragment);
            meTransation.commit();
        }
    }

    //显示Fragment
    private void showFragment(Fragment fragment) {
        if (fragment != null) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            hideAllFragment(transaction);
            transaction.show(fragment);
            transaction.commitAllowingStateLoss();
        }
    }

    //隐藏所有的Fragment
    private void hideAllFragment(FragmentTransaction transaction) {
        if (startFragment != null) {
            transaction.hide(startFragment);
        }

        if (squareFragment != null) {
            transaction.hide(squareFragment);
        }

        if (chatFragment != null) {
            transaction.hide(chatFragment);
        }

        if (meFragment != null) {
            transaction.hide(meFragment);
        }
    }

    //切换主页选项卡 0-星球 1-广场 2-聊天 3-我的
    private void checkMainTab(int index) {
        switch (index) {
            case 0:
                showFragment(startFragment);
                ivStar.setImageResource(R.drawable.img_star_p);
                ivSquare.setImageResource(R.drawable.img_square);
                ivChat.setImageResource(R.drawable.img_chat);
                ivMe.setImageResource(R.drawable.img_me);

                tvStar.setTextColor(getResources().getColor(R.color.colorAccent));
                tvSquare.setTextColor(getResources().getColor(R.color.color_666));
                tvChat.setTextColor(getResources().getColor(R.color.color_666));
                tvMe.setTextColor(getResources().getColor(R.color.color_666));
                break;
            case 1:
                showFragment(squareFragment);
                ivStar.setImageResource(R.drawable.img_star);
                ivSquare.setImageResource(R.drawable.img_square_p);
                ivChat.setImageResource(R.drawable.img_chat);
                ivMe.setImageResource(R.drawable.img_me);

                tvStar.setTextColor(getResources().getColor(R.color.color_666));
                tvSquare.setTextColor(getResources().getColor(R.color.colorAccent));
                tvChat.setTextColor(getResources().getColor(R.color.color_666));
                tvMe.setTextColor(getResources().getColor(R.color.color_666));
                break;
            case 2:
                showFragment(chatFragment);
                ivStar.setImageResource(R.drawable.img_star);
                ivSquare.setImageResource(R.drawable.img_square);
                ivChat.setImageResource(R.drawable.img_chat_p);
                ivMe.setImageResource(R.drawable.img_me);

                tvStar.setTextColor(getResources().getColor(R.color.color_666));
                tvSquare.setTextColor(getResources().getColor(R.color.color_666));
                tvChat.setTextColor(getResources().getColor(R.color.colorAccent));
                tvMe.setTextColor(getResources().getColor(R.color.color_666));
                break;
            case 3:
                showFragment(meFragment);
                ivStar.setImageResource(R.drawable.img_star);
                ivSquare.setImageResource(R.drawable.img_square);
                ivChat.setImageResource(R.drawable.img_chat);
                ivMe.setImageResource(R.drawable.img_me_p);

                tvStar.setTextColor(getResources().getColor(R.color.color_666));
                tvSquare.setTextColor(getResources().getColor(R.color.color_666));
                tvChat.setTextColor(getResources().getColor(R.color.color_666));
                tvMe.setTextColor(getResources().getColor(R.color.colorAccent));
                break;
        }
    }

    /**
     * 防止重叠
     * 当应用的内存紧张的时候系统,会回收Fragment对象
     * 再一次进入的时候会重新创建Fragment
     * 非原来对象,我们无法控制,导致重叠
     *
     * @param fragment
     */
    @Override
    public void onAttachFragment(Fragment fragment) {
        if (startFragment != null && fragment instanceof StartFragment) {
            startFragment = (StartFragment) fragment;
        }

        if (squareFragment != null && fragment instanceof SquareFragment) {
            squareFragment = (SquareFragment) fragment;
        }

        if (chatFragment != null && fragment instanceof ChatFragment) {
            chatFragment = (ChatFragment) fragment;
        }

        if (meFragment != null && fragment instanceof MeFragment) {
            meFragment = (MeFragment) fragment;
        }
    }

    //请求权限
    private void requestPermission() {
        //危险权限
        request( new OnPermissionsResult() {


            @Override
            public void OnSuccess() {

            }

            @Override
            public void OnFail(List<String> noPermissions) {
                LogUtils.i("noPermissions:" + noPermissions.toString());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_star:
                checkMainTab(0);
                break;
            case R.id.ll_square:
                checkMainTab(1);
                break;
            case R.id.ll_chat:
                checkMainTab(2);
                break;
            case R.id.ll_me:
                checkMainTab(3);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == UPLOAD_REQUEST_CODE) {
                //说明上传头像成功
                checkToken();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable!=null){
            if (!disposable.isDisposed()) {
                disposable.dispose();
            }
        }
    }
}
